package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/spf13/cast"
	"goravel/app/models"
)

type HistoryplayerController struct {
	//Dependent services
}

func NewHistoryplayerController() *HistoryplayerController {
	return &HistoryplayerController{
		//Inject services
	}
}

func (r *HistoryplayerController) Index(ctx http.Context) http.Response {
	//从登录日志中获取退出时间最近的一条记录，按照
	//原生db查询,分页
	current_page := cast.ToInt(ctx.Request().Query("current_page", "1"))
	page_size := cast.ToInt(ctx.Request().Query("page_size", "10"))

	loginLogs := []models.LoginLog{}
	facades.Orm().Query().Raw("select distinct  "+
		"a.* from loginlogs a left join loginlogs b on a.stream_id = b.stream_id group by a.stream_id ,a.login_type"+
		" order by a.stream_id ,a.login_type ,a.action_time desc"+
		//分页
		" limit ?,?", current_page, page_size).
		Scan(&loginLogs)
	//总数
	total := 0
	facades.Orm().Query().Raw("select count(*) as total from (select distinct  " +
		"a.* from loginlogs a left join loginlogs b on a.stream_id = b.stream_id group by a.stream_id ,a.login_type" +
		" order by a.stream_id ,a.login_type ,a.action_time desc" +
		") as c").Scan(&total)

	return ctx.Response().Json(http.StatusOK, http.Json{
		"message": "查询成功",
		"data": map[string]interface{}{
			"loginLogs": loginLogs,
			"total":     total,
		},
	})
}

// 历史登录玩家
func (r *HistoryplayerController) PlayerLoginHistory(ctx http.Context) http.Response {
	type PlayerLoginHistory struct {
		LoginDate string `json:"login_date"`
		LoginTime string `json:"login_time"`
		UserName  string `json:"user_name"`
		SteamId   string `json:"steam_id"`
		IsAdd     int    `json:"is_add"`
	}
	//最后一次登录时间，最新登录玩家
	sql := `
SELECT l1.*
FROM loginlogs l1
LEFT JOIN loginlogs l2
ON (l1.stream_id = l2.stream_id AND l1.action_time < l2.action_time)
WHERE l2.stream_id IS NULL 
AND l1.login_type = 'in' 
AND l1.action_time > CURDATE() - INTERVAL 1 DAY;`
	loginLogs := []models.LoginLog{}
	facades.Orm().Query().Raw(sql).Scan(&loginLogs)
	//这些玩家与gatherplayer表中的玩家进行比对，用steam_id进行比对,如果存在表示是新玩家，如果不存在表示是老玩家
	var playerLoginHistory []PlayerLoginHistory
	for _, loginLog := range loginLogs {
		var gatherplayer models.Gatherplayer
		facades.Orm().Query().Model(&models.Gatherplayer{}).Where("steam_id=?", loginLog.StreamId).First(&gatherplayer)
		var isAdd int
		if gatherplayer.ID == 0 {
			isAdd = 1
		} else {
			isAdd = 0
		}
		playerLoginHistory = append(playerLoginHistory, PlayerLoginHistory{
			LoginDate: loginLog.ActionTime,
			LoginTime: loginLog.ActionTime,
			UserName:  loginLog.UserName,
			SteamId:   loginLog.StreamId,
			IsAdd:     isAdd,
		})
	}
	return nil
}
